<template>
  <view>
    <u-form
      ref="uForm"
      :model="form"
      :error-type="errorType"
      label-align="left"
      label-width="80"
      style="background: white; padding: 0 30upx"
    >
      <!-- 循环生成上传组件-->
      <view v-for="(img, imgIndex) in form.images" :key="imgIndex" class="upload-item">
        <u-form-item label="图片" prop="images">
          <u-upload
            :max-size="3 * 1024 * 1024"
            max-count="1"
            :file-list="img.faceList"
            :deletable="false"
            name="files"
          />
          <u-upload
            :ref="'uUpload' + imgIndex"
            :max-size="3 * 1024 * 1024"
            max-count="1"
            :action="`${getUploadApp}`"
            :file-list="img.fileList"
            name="files"
            :form-data="{
              name: 'curative',
              type: 'taskUploads'
            }"
            :header="{Authorization: `Bearer ${token}`}"
            :before-upload="beforeUpload"
            @on-success="(data, fileIndex) => handleSuccess(imgIndex, data, fileIndex)"
            @on-remove="(fileIndex, lists) => handleRemove(imgIndex, fileIndex, lists)"
          />
        </u-form-item>
      </view>
    </u-form>
    <view class="btnBox bottoms">
      <u-button
        style="width: 300rpx; border-radius: 50rpx"
        type="primary"
        @click="submit()"
      >
        图片保存
      </u-button>
    </view>
    <view>
      <u-toast ref="uToast" />
    </view>
  </view>
</template>

<script>
export default {
  components: {},
  props: {
    type: {
      type: String,
      required: true
    },
    // eslint-disable-next-line vue/require-default-prop
    data: {
      type: Array,
      required: []
    },
    // eslint-disable-next-line vue/require-default-prop
    eventChannel: {
      type: Object,
      required: false
    }
  },
  data() {
    return {
      errorType: ['message'],
      mode: 'date', // 选择模式（range:范围,date:单选）http://124.221.253.237:99
      token: '',
      baseURL: '',
      getUploadApp: '',
      compressQuality: 0.8, // 压缩质量 0-1
      maxWidth: 1024, // 最大宽度
      form: {
        images: []
      },
      rules: {
        cusName: [
          {
            required: true,
            message: '请输入*客户*',
            trigger: ['change', 'blur']
          }
        ],
        tempCreditQty: [
          {
            // eslint-disable-next-line no-unused-vars
            validator: (rule, value, callback) => {
              if (value === '') {
                return false
              }
              return true
            },
            message: '请输入*临时信用额*',
            trigger: ['change', 'blur']
          }
        ]
      },
      imagesList: [],
      KeyboardHeight: 0
    }
  },
  // # 子组件加载完毕后绑定表单验证规则
  mounted() {
    this.$refs.uForm.setRules(this.rules)
    uni.onKeyboardHeightChange((res) => {
      this.KeyboardHeight = res.height
    })
    setTimeout(() => {
      this.getOrganList()
    }, 300)
  },
  methods: {
    async getOrganList() {
      this.token = uni.getStorageSync('token')
      this.baseURL = uni.getStorageSync('baseURL')
      this.getUploadApp = uni.getStorageSync('getUploadApp')
      this.$u.api.getImagesUpload({ name: 'curative' }).then(res => {
        if (res.code === 200) {
          res.data.pageItems.forEach(e => {
            this.data.forEach(item => {
              if (e.path === item.curePhoto) {
                item.imagesId = e.id
              }
            })
          })
          this.imagesList = res.data.pageItems
          this.form.images = this.data
        }
      })
    },
    // # 提交表单，进行校验
    submit() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.eventChannel.emit('someEvent', { data: this.form.images })
          uni.navigateBack({
            delta: 1
          })
        } else {
          console.log('验证失败')
        }
      })
    },
    // 上传成功回调
    handleSuccess(imgIndex, data, fileIndex) {
      if (data.code === 200) { // 根据你的接口返回结构调整
        this.showToast('上传成功！', 'success')
        this.form.images[imgIndex].curePhoto = data.data.path
        this.$u.api.getImagesUpload({ name: 'curative' }).then(res => {
          if (res.code === 200) {
            res.data.pageItems.forEach(e => {
              this.form.images.forEach(item => {
                if (e.path === item.curePhoto) {
                  item.imagesId = e.id
                }
              })
            })
            this.imagesList = res.data.pageItems
          }
        })
      }
    },
    // 图片压缩方法
    async beforeUpload(index, list) {
      try {
        const file = list[index]
        const src = file.url

        // 1. 获取图片信息
        const { width, height } = await this.getImageInfo(src)

        // 2. 动态计算压缩参数
        let targetWidth = width
        let targetHeight = height
        const quality = 70 // 初始质量

        // 尺寸超过1200px则缩放
        if (width > 1200 || height > 1200) {
          const scale = Math.min(1200 / width, 1200 / height)
          targetWidth = Math.floor(width * scale)
          targetHeight = Math.floor(height * scale)
        }

        // 3. 执行压缩
        const { tempFilePath } = await this.compressImage(src, targetWidth, targetHeight, quality)

        // 4. 检查压缩后大小
        const { size } = await this.getFileInfo(tempFilePath)
        if (size > 1 * 1024 * 1024) {
          throw new Error('压缩后仍超过1MB')
        }

        // 5. 替换为压缩后的文件
        const newFile = { ...file, url: tempFilePath }
        const newList = [...list]
        newList.splice(index, 1, newFile)

        return newList // 返回新文件列表
      } catch (error) {
        uni.showToast({ title: '压缩失败: ' + error.message, icon: 'none' })
        return false // 阻止上传
      }
    },
    // 获取图片信息
    getImageInfo(src) {
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src,
          success: resolve,
          fail: reject
        })
      })
    },
    // 压缩图片
    compressImage(src, width, height, quality) {
      return new Promise((resolve, reject) => {
        uni.compressImage({
          src,
          quality,
          width: width + 'px',
          height: height + 'px',
          success: resolve,
          fail: reject
        })
      })
    },
    // 获取文件大小
    getFileInfo(filePath) {
      return new Promise((resolve, reject) => {
        uni.getFileInfo({
          filePath,
          success: resolve,
          fail: reject
        })
      })
    },
    // 删除图片
    handleRemove(imgIndex, fileIndex, lists) {
      this.form.images[imgIndex].fileList = [...lists]
      this.form.images[imgIndex].curePhoto = ''
      const imagesId = this.form.images[imgIndex].imagesId
      if (imagesId) {
        this.$u.api.getDeteleUpload({ id: imagesId, name: 'curative', type: 'taskUploads' }).then(res => {
          if (res.code === 200) {
            this.form.images[imgIndex].curePhoto = ''
          }
        })
          .catch(err => {
            console.log(err)
          })
      }
    },
    // 图片预览
    previewImage(current) {
      const urls = this.form.image.map(item => item.url)
      uni.previewImage({
        current,
        urls
      })
    },
    showToast(e, type) {
      this.$refs.uToast.show({
        title: e,
        type: type
      })
    }
  }
}
</script>

<style lang="scss">
  @import './index.scss';
</style>
